package com.ruoyi.activiti.modeler.listener;

import com.ruoyi.activiti.modeler.utils.SpringUtil;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.persistence.entity.IdentityLinkEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.logging.Logger;

@Service("myUserTaskListener")
public class MyUserTaskListener implements TaskListener {
    @Override
    public void notify(DelegateTask delegateTask) {
        Logger.getLogger("MyListener").info("######## 进入任务监听节点");
        String taskId = delegateTask.getId();
        Logger.getLogger("MyListener").info("任务id："+ taskId + ";  " +
                "任务名："+delegateTask.getName() + "; " +
                "执行人："+delegateTask.getAssignee());
        ArrayList<IdentityLinkEntity> candidates = new ArrayList(delegateTask.getCandidates());
        if (!CollectionUtils.isEmpty(candidates)) {
            // 候选人需要代理，新建一个identityLink，删掉原有的
            for (int i = 0; i < candidates.size(); i++) {
                IdentityLinkEntity identityLink = candidates.get(i);
                String fromUserId = identityLink.getUserId();
                Logger.getLogger("MyListener").info("候选人id：" + fromUserId);
                Logger.getLogger("MyListener").info("候选人类型："+ identityLink.getType());
                String processId = identityLink.getTask().getProcessDefinitionId();
                String key = SpringUtil.getObject(RepositoryService.class).getProcessDefinition(processId).getKey();
                String toUserId = "testData：sgw";// todo： 查出设置代理人的数据
                if (StringUtils.isNotBlank(toUserId)) {
                    // 第一种写法：成功，且在hi_identity表添加代理信息，方便查询
                    delegateTask.deleteCandidateUser(fromUserId);
                    delegateTask.addCandidateUser(toUserId);
                    Logger.getLogger("MyListener").info("######### 设置代理成功：" + toUserId);
                }
            }
        }
    }
}
